package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.jdbc.core.JdbcTemplate

public class auto5GSendMSG implements CallBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(auto5GSendMSG.class);

    private static String api_Domain = "http://127.0.0.1:8080";
    private static String serverRoot = "http://h5.sz-water.com.cn";
    private static String serviceId = "471";// 应用ID

    private static String sendTrigger5Gmsg_URL = "http://h5.sz-water.com.cn/api/open-api/v1/msg/sendTrigger5Gmsg";
    private static String sendDynamicTrigger5Gmsg_URL = "http://h5.sz-water.com.cn/api/open-api/v1/msg/sendDynamicTrigger5Gmsg";

    private static String updateDocSQL = ""; // 应用ID

    private static JdbcTemplate jt = new JdbcTemplate();

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        log.warn("---auto5GSendMessage---");
        api_Domain = KHDBConfig.getAPIURL(eliteBean, "EliteInner-API");
        serverRoot = KHDBConfig.getAPIURL(eliteBean, "5G-SMS-serverRoot");
        serviceId = KHDBConfig.getParamConfig(eliteBean, "5G-SMS-serviceId");

        sendTrigger5Gmsg_URL = KHDBConfig.getAPIURL(eliteBean, "5G-SMS-sendTrigger5Gmsg");
        sendDynamicTrigger5Gmsg_URL = KHDBConfig.getAPIURL(eliteBean, "5G-SMS-sendDynamicTrigger5Gmsg");


        jt = new JdbcTemplate(eliteBean.getDataSource());

        //查找待发送任务
        List getSmsSelectSQL = eliteBean.chaxun_sql('''Select Documentout_Guid,
                                                               Doctype,
                                                               Documentto,
                                                               Documentpath,
                                                               Documentpath2,
                                                               Lockedby,
                                                               '' Openid,
                                                               Template_Id,
                                                               Stringfield1,
                                                               '' Msgid
                                                          From Documentout With(Nolock)
                                                         Where Doctype = 6
                                                           And Status = 3
                                                           And Sub_Doctype = '1'
                                                           And Trialcount < Trialcountlimit
                                                           And Isnull(Expectedstartdate, Getdate()) <= Getdate()
                                                         Order By Priority_Id, Isnull(Expectedstartdate, Getdate()), Createddate''', "dataSource");
        log.debug("SQL获取待发送数据量:" + getSmsSelectSQL.size());

        for (int i = 0; i < getSmsSelectSQL.size(); i++) {

            Map selectResultcm = getSmsSelectSQL.get(i);
            String Documentout_Guid = selectResultcm.get("Documentout_Guid");
            String Doctype = selectResultcm.get("Doctype");
            String Documentto = selectResultcm.get("Documentto");
            String Documentpath2 = selectResultcm.get("Documentpath2");
            String Template_Id = selectResultcm.get("Template_Id");
            String Msgid = selectResultcm.get("Msgid");

            if (Doctype == "6") {
                doSendSMS(Documentout_Guid, Documentto, Documentpath2, Msgid, Template_Id);

            } else {
                log.warn("未知的消息类型-本条任务结束");
            }
        }

    }

    /**
     * 发送短信消息
     * @param s1
     * @param s2
     * @param s3
     */
    public static void doSendSMS(String Documentout_Guid, String Documentto, String Documentpath2, String Msgid, String Template_Id) {

        // 开始准备发送
        JSONObject sendResultJson = new JSONObject();
        if (KHUtil.isNull(Documentpath2) || Documentpath2 == "[]") {
            sendResultJson = sendTrigger5Gmsg(Documentout_Guid, Documentto, Documentpath2, Msgid, Template_Id);
        } else {
            sendResultJson = sendDynamicTrigger5Gmsg(Documentout_Guid, Documentto, Documentpath2, Msgid, Template_Id);
        }

        // 解析返回信息LockedBy
        String resCode = sendResultJson.has("code") ? sendResultJson.getString("code") : "-1";
        String resDesc = sendResultJson.has("msg") ? sendResultJson.getString("msg") : "";
        String msgId = sendResultJson.has("msgId") ? sendResultJson.getString("msgId") : "";

        if (sendResultJson.getString("code") == "200") {
            // 发送成功
            updateDocSQL = '''Update Documentout
                               Set Status          = 1,
                                   Passflag        = 1,
                                   Resultcode      = ?,
                                   Lasttrydatetime = Getdate(),
                                   Modifiedby      = 'SELITE',
                                   Modifieddate    = Getdate(),
                                   Failcode        = ?,
                                   Faildescription = ?,
                                   Trialcount      = Isnull(Trialcount, 0) + 1,
                                   Usermsgid       = ?
                             Where Documentout_Guid = ?''';

            int updateDocSQLRes = jt.update(updateDocSQL, msgId, resCode, resDesc, msgId, Documentout_Guid);
            log.debug("5G短信平台发送短信-短信平台回写Documentout表SQL执行结果:" + updateDocSQLRes);
        } else {
            // 发送失败
            updateDocSQL = '''Update Documentout
                               Set Status = Case
                                              When Isnull(Trialcount, 0) + 1 >= Isnull(Trialcountlimit, 3) Then
                                               '-1'
                                              Else
                                               Status
                                            End,
                                   Failcode        = ?,
                                   Faildescription = ?,
                                   Trialcount      = Isnull(Trialcount, 0) + 1,
                                   Lasttrydatetime = Getdate(),
                                   Usermsgid       = ?
                             Where Documentout_Guid = ?''';

            int updateDocSQLRes = jt.update(updateDocSQL, resCode, resDesc, msgId, Documentout_Guid);
            log.debug("5G短信平台发送短信-短信平台回写Documentout表SQL执行结果:" + updateDocSQLRes);
        }

    }

    // 5G发送-无参数
    public static JSONObject sendTrigger5Gmsg(String Documentout_Guid, String Documentto, String Documentpath2, String Msgid, String Template_Id) {
        JSONObject resultSendSms = new JSONObject();

        log.debug("5G消息触发-参数-Documentout_Guid:" + Documentout_Guid + " Documentto:" + Documentto + " Documentpath2:" + Documentpath2 + " Msgid:" + Msgid + " Template_Id:" + Template_Id);

        try {
            // 获取发送所需要的Token
            JSONObject apiTokenJson = JSONObject.fromObject(Util.doHttpGet(api_Domain + "/apiGetToken?appid=5GSMS", "UTF-8", 5000, 0));
            String access_token = apiTokenJson.getJSONObject("data").getString("access_token");
            log.debug("5G消息触发-Token结果:" + access_token);

            // 处理头文件
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json");
            headParams.put("Authorization", "Bearer " + access_token);
            headParams.put("serverRoot", serverRoot);

            JSONObject postJson = new JSONObject();
            postJson.put("templateId", Template_Id);
            postJson.put("serviceId", serviceId);

            JSONArray mobileNos = new JSONArray();
            mobileNos.add(Documentto);
            postJson.put("mobileNos", mobileNos);

            log.debug("5G消息触发-调用地址:" + sendTrigger5Gmsg_URL + " 调用参数信息:" + postJson.toString());

            String resultInfo = Util.doHttpPostUseHead(sendTrigger5Gmsg_URL, postJson.toString(), "UTF-8", 120000, 0, headParams);
            log.debug("5G消息触发-调用结果:" + resultInfo);

            JSONObject resultJson = JSONObject.fromObject(resultInfo);
            String code = resultJson.getInt("code");

            resultSendSms.put("code", resultJson.getInt("code"));
            resultSendSms.put("msg", resultJson.getString("msg"));

            if (code == "200") {
                String msgId = "";
                if (KHUtil.isNull(msgId)) {
                    JSONArray successArr = resultJson.getJSONObject("data").getJSONArray("success");
                    log.debug("5G消息触发-successArr 结果：" + successArr.toString());
                    for (int i = 0; i < successArr.size(); i++) {
                        JSONObject successObj = successArr.getJSONObject(i);
                        if (Documentto == successObj.getString("phone")) {
                            msgId = successObj.getString("messageId");
                            resultSendSms.put("msgId", msgId);
                            resultSendSms.put("resultCode", "1");
                            break;
                        }
                    }
                }

                if (KHUtil.isNull(msgId)) {
                    JSONArray failArr = resultJson.getJSONObject("data").getJSONArray("fail");
                    log.debug("5G消息触发-failArr 结果：" + failArr.toString());
                    for (int i = 0; i < failArr.size(); i++) {
                        JSONObject successObj = failArr.getJSONObject(i);
                        if (Documentto == successObj.getString("phone")) {
                            msgId = "";
                            resultSendSms.put("resultCode", "-1");
                            break;
                        }
                    }
                }
                log.debug("5G消息触发-SuccessList结果：" + resultJson.getJSONObject("data").getJSONArray("success").toString());
            }

            log.debug("5G消息触发-结果：" + resultSendSms.toString());

        } catch (Exception e1) {
            log.error("5G消息触发-异常：", e1);
            resultSendSms.put("code", "-1");
            resultSendSms.put("msg", e1.getMessage());

        }

        return resultSendSms;
    }

    // 5G发送-有参数
    public static JSONObject sendDynamicTrigger5Gmsg(String Documentout_Guid, String Documentto, String Documentpath2, String Msgid, String Template_Id) {
        JSONObject resultSendSms = new JSONObject();

        log.debug("5G消息动态变量模板触发-参数-Documentout_Guid:" + Documentout_Guid + " Documentto:" + Documentto + " Documentpath2:" + Documentpath2 + " Msgid:" + Msgid + " Template_Id:" + Template_Id);

        try {
            // 获取发送所需要的Token
            JSONObject apiTokenJson = JSONObject.fromObject(Util.doHttpGet(api_Domain + "/apiGetToken?appid=5GSMS", "UTF-8", 5000, 0));
            String access_token = apiTokenJson.getJSONObject("data").getString("access_token");
            log.debug("5G消息动态变量模板触发-Token结果:" + access_token);

            // 处理头文件
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json");
            headParams.put("Authorization", "Bearer " + access_token);
            headParams.put("serverRoot", serverRoot);

            // 组装调用参数
            JSONObject postJson = new JSONObject();
            postJson.put("templateId", Template_Id);
            postJson.put("serviceId", serviceId);

            // 组装dynamicInfo
            JSONObject dynamicInfo = new JSONObject();
            dynamicInfo.put("mobileNo", Documentto);
            dynamicInfo.put("dynamicMultivariable", JSONArray.fromObject(Documentpath2));

            JSONArray dynamicInfoArr = new JSONArray();
            dynamicInfoArr.add(dynamicInfo);

            postJson.put("dynamicInfo", dynamicInfoArr);

            log.debug("5G消息动态变量模板触发-调用地址:" + sendDynamicTrigger5Gmsg_URL + " 调用参数信息:" + postJson.toString());

            String resultInfo = Util.doHttpPostUseHead(sendDynamicTrigger5Gmsg_URL, postJson.toString(), "UTF-8", 120000, 0, headParams);
            log.debug("5G消息动态变量模板触发-调用结果:" + resultInfo);

            JSONObject resultJson = JSONObject.fromObject(resultInfo);
            String code = resultJson.getInt("code");

            resultSendSms.put("code", resultJson.getInt("code"));
            resultSendSms.put("msg", resultJson.getString("msg"));

            if (code == "200") {
                String msgId = "";
                if (KHUtil.isNull(msgId)) {
                    JSONArray successArr = resultJson.getJSONObject("data").getJSONArray("success");
                    log.debug("5G消息动态变量模板触发-successArr 结果：" + successArr.toString());
                    for (int i = 0; i < successArr.size(); i++) {
                        JSONObject successObj = successArr.getJSONObject(i);
                        if (Documentto == successObj.getString("phone")) {
                            msgId = successObj.getString("messageId");
                            resultSendSms.put("msgId", msgId);
                            resultSendSms.put("resultCode", "1");
                            break;
                        }
                    }
                }

                if (KHUtil.isNull(msgId)) {
                    JSONArray failArr = resultJson.getJSONObject("data").getJSONArray("fail");
                    log.debug("5G消息动态变量模板触发-failArr 结果：" + failArr.toString());
                    for (int i = 0; i < failArr.size(); i++) {
                        JSONObject successObj = failArr.getJSONObject(i);
                        if (Documentto == successObj.getString("phone")) {
                            msgId = "";
                            resultSendSms.put("resultCode", "-1");
                            break;
                        }
                    }
                }
            }

            log.debug("5G消息动态变量模板触发-结果：" + resultSendSms.toString());

        } catch (Exception e1) {
            log.error("5G消息动态变量模板触发-异常：", e1);
            resultSendSms.put("code", "-1");
            resultSendSms.put("msg", e1.getMessage());

        }

        return resultSendSms;
    }
}